﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Croxweb.Leuphana.Services.MyStudyService;
using Croxweb.Leuphana.Services.StorageService;
using System.Windows.Data;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Threading;


namespace Croxweb.Leuphana.ViewModels
{
    public class PersonSearchViewModel : ViewModelBase
    {
        private readonly IMyStudyService service;
        private readonly ISettingStore config;

        private CollectionViewSource searchResults = new CollectionViewSource();

        private ObservableCollection<PersonViewModel> persons;

        private Boolean isSearching;


        // Constructor.
        public PersonSearchViewModel(IMyStudyService service, ISettingStore config)
        {
            this.service = service;
            this.config = config;

            persons = new ObservableCollection<PersonViewModel>();
            searchResults.Source = persons;
        }


        // Status property.
        public Boolean IsSearching
        {
            get { return isSearching; }
            set
            {
                isSearching = value;
                NotifyPropertyChanged("IsSearching");
            }
        }


        // List property.
        public ICollectionView SearchResults { get { return searchResults.View; } }

        
        // Activities.
        public void Search(String name)
        {
            if (!isSearching)
            {
                IsSearching = true;

                service.SearchPersons(name, (result, foundPersons) =>
                {
                    // Add persons to result list.
                    if (result == MyStudyResult.Success)
                    {
                        persons = new ObservableCollection<PersonViewModel>();

                        foundPersons.ToList().ForEach((p) =>
                        {
                            persons.Add(new PersonViewModel(p));
                        });

                        searchResults = new CollectionViewSource() { Source = persons };
                        searchResults.View.MoveCurrentToPosition(-1);

                        NotifyPropertyChanged(String.Empty);
                    }

                    IsSearching = false;
                });
            }
        }
    }
}
